using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;

namespace Emlyn.Common.Data.SqlServer.SqlManagers
{
    public class SqlManagerScope: IDisposable
    {
        int _connectionIndex;
        bool _isCommitted;

        private void BeginTransaction()
        {
            _isCommitted = false;
            SqlManager.GetManagerConnection(_connectionIndex).BeginTransaction();
        }

        public SqlManagerScope()
        {
            _connectionIndex = 0;
            BeginTransaction();
        }

        public SqlManagerScope(int aConnectionIndex)
        {
            _connectionIndex = aConnectionIndex;
            BeginTransaction();
        }

        public SqlConnection Connection
        {
            get
            {
                return SqlManager.GetManagerConnection(_connectionIndex).Connection;
            }
        }

        public SqlTransaction Transaction
        {
            get
            {
                return SqlManager.GetManagerConnection(_connectionIndex).Transaction;
            }
        }

        public void Commit()
        {
            if (_isCommitted)
                throw new ApplicationException("Can't call Commit twice on one SqlManageScope");

            SqlManager.GetManagerConnection(_connectionIndex).Commit();
            _isCommitted = true;
        }

        public SqlDataReader GetReader(string aSQL, List<SqlParameter> aParams)
        {
            SqlCommand cmd = new SqlCommand(aSQL, Connection);
            cmd.Transaction = Transaction;

            if (aParams != null)
            {
                foreach (SqlParameter lParam in aParams)
                {
                    cmd.Parameters.Add(lParam);
                }
            }

            return cmd.ExecuteReader();
        }

        #region IDisposable Members

        public void Dispose()
        {
            if (!_isCommitted)
            {
                SqlManager.GetManagerConnection(_connectionIndex).Rollback();
            }
        }

        #endregion
    }
}
